package com.blkj.iam.common.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Ethan
 * createTime 2024/10/31 08:34
 * description
 * version 1.0
 */
@Slf4j
public class HttpSender {

    private final OkHttpClient client;

    public HttpSender() throws Exception {
        // 创建 OkHttpClient 实例
        this.client = new OkHttpClient.Builder().sslSocketFactory(UnsafeSSLContext.createUnsafeSSLContext().getSocketFactory(), new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }).hostnameVerifier((hostname, session) -> true).connectTimeout(600, TimeUnit.SECONDS).readTimeout(600, TimeUnit.SECONDS).writeTimeout(600, TimeUnit.SECONDS).build();

    }

    // GET 请求
    public String get(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(url).get();

        // 添加请求头
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    // GET 请求
    public String get(String url) throws IOException {
        String replace = url.replaceAll("//+", "/").replaceAll("http:/", "http://");
        log.info("GET请求URL: {}", replace);
        Request.Builder requestBuilder = new Request.Builder().url(replace).get();

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    // POST 请求
    public String post(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), json);

        Request.Builder requestBuilder = new Request.Builder().url(url).post(body);

        // 添加请求头
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    // POST 请求
    public String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), json);
        String replace = url.replaceAll("//+", "/").replaceAll("http:/", "http://");
        Request.Builder requestBuilder = new Request.Builder().url(replace).post(body);
        log.info("POST请求URL: {}, 请求参数: {}", replace, json);

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }
}
